import models from "@/config/models.json";
import prompts from "@/config/prompts.json";
import {type OpenaiConfig, useOpenaiConfig} from "@/lib/store";
import type {AiModel, TodoItem} from "@/lib/types";
import {createOpenAI} from "@ai-sdk/openai";
import {generateText} from "ai";

export class AiService {
    static async generateComponent(prompt: string, model: string, config: OpenaiConfig): Promise<string> {
        try {
            const modelProvider = this.getModelProvider(model, config);

            const systemPrompt = prompts.generateComponent.systemPrompt;

            const { text } = await generateText({
                model: modelProvider,
                prompt: prompt,
                system: systemPrompt,
                temperature: 0.7,
                maxTokens: 2048,
            });

            return text;
        } catch (error) {
            console.error("Error generating component:", error);
            throw new Error("组件生成失败，请稍后重试");
        }
    }

    static async generateTodoList(prompt: string, model: string, config: OpenaiConfig): Promise<TodoItem[]> {
        try {
            const modelProvider = this.getModelProvider(model, config);

            const systemPrompt = prompts.generateTodoList.systemPrompt;

            const { text } = await generateText({
                model: modelProvider,
                prompt: prompt,
                system: systemPrompt,
                temperature: 0.7,
                maxTokens: 2000,
            });

            // 尝试解析返回的JSON
            try {
                // 有时AI可能会在JSON前后添加额外文本，尝试提取JSON部分
                const jsonMatch = text.match(/\[[\s\S]*\]/);
                const jsonText = jsonMatch ? jsonMatch[0] : text;

                const todoList = JSON.parse(jsonText) as TodoItem[];

                // 确保每个项目都有必要的字段
                return todoList.map((item, index) => ({
                    id: item.id || index + 1,
                    title: item.title || `任务 ${index + 1}`,
                    description: item.description || "",
                    priority: item.priority || "medium",
                    status: item.status || "todo",
                    selected: false,
                }));
            } catch (parseError) {
                console.error("Error parsing TodoList JSON:", parseError);
                throw new Error("无法解析AI返回的任务列表，请重试");
            }
        } catch (error) {
            console.error("Error generating TodoList:", error);
            throw new Error("任务列表生成失败，请稍后重试");
        }
    }

    static async generateProjectStructure(todoItems: TodoItem[], model: string, config: OpenaiConfig): Promise<string> {
        try {
            const modelProvider = this.getModelProvider(model, config);

            // 构建任务描述文本
            const tasksDescription = todoItems.map((item) => `${item.id}. ${item.title}: ${item.description}`).join("\n");

            const prompt = `
    基于以下任务列表，生成一个Vue3+TypeScript+Vite+TailwindCSS项目的文件结构：
    ${tasksDescription}
    请提供一个完整的项目目录结构，包括所有需要的文件和文件夹。
    `;

            const systemPrompt = prompts.generateProjectStructure.systemPrompt;

            const { text } = await generateText({
                model: modelProvider,
                prompt: prompt,
                system: systemPrompt,
                temperature: 0.7,
                maxTokens: 1500,
            });

            return text;
        } catch (error) {
            console.error("Error generating project structure:", error);
            throw new Error("项目结构生成失败，请稍后重试");
        }
    }

    static getAvailableModels(): AiModel[] {
        return models;
    }
    
    private static getModelProvider(modelId: string, config: OpenaiConfig) {
        const openai = createOpenAI({
            apiKey: config.apiKey,
            baseURL: config.baseURL,
        });

        if (modelId.startsWith("qwen")) {
            return openai(modelId);
        } else {
            console.warn(`Model ${modelId} not supported, falling back to qwen-max-2025-01-25`);
            return openai("qwen-max-2025-01-25");
        }
    }
}
